import React, { useState, useEffect } from 'react'
import { aiService } from '../services/aiService'

interface APIStatus {
  openai_configured: boolean
  openrouter_configured: boolean
  groq_configured: boolean
  has_any_key: boolean
  current_mode: string
}

export const Settings: React.FC = () => {
  const [apiStatus, setApiStatus] = useState<APIStatus | null>(null)
  const [selectedProvider, setSelectedProvider] = useState<'openai' | 'openrouter' | 'groq'>('groq')
  const [apiKey, setApiKey] = useState('')
  const [isLoading, setIsLoading] = useState(false)
  const [message, setMessage] = useState('')
  const [showApiKey, setShowApiKey] = useState(false)

  // 加载API状态
  useEffect(() => {
    loadAPIStatus()
  }, [])

  const loadAPIStatus = async () => {
    try {
      const status = await aiService.checkAPIStatus()
      setApiStatus(status.status)
    } catch (error) {
      console.error('加载API状态失败:', error)
    }
  }

  const handleSaveConfig = async () => {
    if (!apiKey.trim()) {
      setMessage('请输入API密钥')
      return
    }

    setIsLoading(true)
    setMessage('')

    try {
      const response = await fetch('/api/ai/configure', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          provider: selectedProvider,
          api_key: apiKey.trim()
        })
      })

      const result = await response.json()
      
      if (result.success) {
        setMessage(`✅ ${result.message}`)
        setApiKey('')
        await loadAPIStatus()
      } else {
        setMessage(`❌ ${result.message}`)
      }
    } catch (error) {
      setMessage(`❌ 配置失败: ${error}`)
    }

    setIsLoading(false)
  }

  const handleClearConfig = async () => {
    setIsLoading(true)
    setMessage('')

    try {
      const response = await fetch('/api/ai/clear-config', {
        method: 'POST'
      })

      const result = await response.json()
      
      if (result.success) {
        setMessage(`✅ ${result.message}`)
        await loadAPIStatus()
      } else {
        setMessage('❌ 清除配置失败')
      }
    } catch (error) {
      setMessage(`❌ 操作失败: ${error}`)
    }

    setIsLoading(false)
  }

  return (
    <div className="max-w-2xl mx-auto p-6 bg-white rounded-lg shadow-md">
      <h2 className="text-2xl font-bold mb-6">AI API 配置</h2>
      
      {/* 当前状态 */}
      <div className="mb-6 p-4 bg-gray-50 rounded-lg">
        <h3 className="font-semibold mb-2">当前状态</h3>
        {apiStatus ? (
          <div className="space-y-2 text-sm">
            <p>模式: <span className={`font-medium ${apiStatus.current_mode === 'demo' ? 'text-orange-600' : 'text-green-600'}`}>
              {apiStatus.current_mode === 'demo' ? '演示模式' : '真实AI模式'}
            </span></p>
            <p>OpenAI: <span className={apiStatus.openai_configured ? 'text-green-600' : 'text-gray-500'}>
              {apiStatus.openai_configured ? '已配置' : '未配置'}
            </span></p>
            <p>OpenRouter: <span className={apiStatus.openrouter_configured ? 'text-green-600' : 'text-gray-500'}>
              {apiStatus.openrouter_configured ? '已配置' : '未配置'}
            </span></p>
            <p>Groq: <span className={apiStatus.groq_configured ? 'text-green-600' : 'text-gray-500'}>
              {apiStatus.groq_configured ? '已配置' : '未配置'}
            </span></p>
          </div>
        ) : (
          <p className="text-gray-500">加载中...</p>
        )}
      </div>

      {/* 配置表单 */}
      <div className="space-y-4">
        <div>
          <label className="block text-sm font-medium mb-2">选择API提供商</label>
          <div className="space-y-3">
            <label className="flex items-center p-3 border border-green-200 rounded-lg bg-green-50">
              <input
                type="radio"
                name="provider"
                value="groq"
                checked={selectedProvider === 'groq'}
                onChange={(e) => setSelectedProvider(e.target.value as 'groq')}
                className="mr-3"
              />
              <div>
                <div className="font-medium text-green-700">🚀 Groq (推荐 - 完全免费)</div>
                <div className="text-sm text-green-600">Llama 3.1 70B/8B、Mixtral 8x7B - 超快速度，完全免费</div>
                <div className="text-xs text-green-700 font-medium">
                  免费注册: <a href="https://console.groq.com" target="_blank" rel="noopener noreferrer" className="underline">https://console.groq.com</a>
                </div>
              </div>
            </label>
            
            <label className="flex items-center p-3 border border-gray-200 rounded-lg">
              <input
                type="radio"
                name="provider"
                value="openrouter"
                checked={selectedProvider === 'openrouter'}
                onChange={(e) => setSelectedProvider(e.target.value as 'openrouter')}
                className="mr-3"
              />
              <div>
                <div className="font-medium">OpenRouter</div>
                <div className="text-sm text-gray-500">支持多种免费AI模型，包括Llama、Gemma等</div>
                <div className="text-xs text-blue-600">
                  注册地址: <a href="https://openrouter.ai" target="_blank" rel="noopener noreferrer" className="underline">https://openrouter.ai</a>
                </div>
              </div>
            </label>
            
            <label className="flex items-center p-3 border border-gray-200 rounded-lg">
              <input
                type="radio"
                name="provider"
                value="openai"
                checked={selectedProvider === 'openai'}
                onChange={(e) => setSelectedProvider(e.target.value as 'openai')}
                className="mr-3"
              />
              <div>
                <div className="font-medium">OpenAI</div>
                <div className="text-sm text-gray-500">GPT-3.5、GPT-4等模型（需要付费）</div>
                <div className="text-xs text-blue-600">
                  获取密钥: <a href="https://platform.openai.com/api-keys" target="_blank" rel="noopener noreferrer" className="underline">https://platform.openai.com/api-keys</a>
                </div>
              </div>
            </label>
          </div>
        </div>

        <div>
          <label className="block text-sm font-medium mb-2">
            API 密钥
            <button
              type="button"
              onClick={() => setShowApiKey(!showApiKey)}
              className="ml-2 text-xs text-blue-600 hover:text-blue-800"
            >
              {showApiKey ? '隐藏' : '显示'}
            </button>
          </label>
          <input
            type={showApiKey ? 'text' : 'password'}
            value={apiKey}
            onChange={(e) => setApiKey(e.target.value)}
            placeholder={selectedProvider === 'groq' ? 'gsk_...' : selectedProvider === 'openrouter' ? 'sk-or-v1-...' : 'sk-...'}
            className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
            disabled={isLoading}
          />
          <p className="text-xs text-gray-500 mt-1">
            您的API密钥将安全存储在本地，不会上传到任何服务器
          </p>
        </div>

        {/* 操作按钮 */}
        <div className="flex space-x-3">
          <button
            onClick={handleSaveConfig}
            disabled={isLoading || !apiKey.trim()}
            className="px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 disabled:opacity-50 disabled:cursor-not-allowed"
          >
            {isLoading ? '配置中...' : '保存配置'}
          </button>
          
          {apiStatus?.has_any_key && (
            <button
              onClick={handleClearConfig}
              disabled={isLoading}
              className="px-4 py-2 bg-gray-600 text-white rounded-md hover:bg-gray-700 disabled:opacity-50"
            >
              {isLoading ? '清除中...' : '清除配置'}
            </button>
          )}
        </div>

        {/* 消息显示 */}
        {message && (
          <div className={`p-3 rounded-md ${
            message.includes('✅') ? 'bg-green-50 text-green-800' : 'bg-red-50 text-red-800'
          }`}>
            {message}
          </div>
        )}
      </div>

      {/* 使用说明 */}
      <div className="mt-8 p-4 bg-blue-50 rounded-lg">
        <h3 className="font-semibold mb-2">💡 使用建议</h3>
        <div className="text-sm space-y-1">
          <p>• <strong>🚀 最佳选择</strong>: Groq API - 完全免费，超快速度，无需信用卡</p>
          <p>• <strong>Groq免费模型</strong>: Llama 3.1 70B、Llama 3.1 8B、Mixtral 8x7B</p>
          <p>• <strong>获取步骤</strong>: 访问 console.groq.com → 注册 → API Keys → 创建密钥</p>
          <p>• <strong>配置后</strong>: 立即享受真正的AI对话，响应速度极快</p>
        </div>
      </div>
    </div>
  )
}